<template>
    <div>
        <!-- 添加/修改页面 -->
        <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin:10px 0;">
            <el-form :inline="false">
                <el-form-item label="SPU名称">
                    <el-input v-model="spuParams.spuName" placeholder="请输入SPU名称"></el-input>
                </el-form-item>
                <el-form-item label="SPU品牌">
                    <el-select v-model="spuParams.tmId" placeholder="请选择" clearable filterable>
                        <el-option :label="trademark.tmName" :value="trademark.id"
                            v-for="(trademark,index) in allTrademark" :key="trademark.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="SPU描述">
                    <el-input v-model="spuParams.description" placeholder="请输入SPU描述" type="textarea" clearable>
                    </el-input>
                </el-form-item>
                <el-form-item label="SPU图片">
                    <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload"
                        list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="销售属性">
                    <el-select v-model="unSaleAttrNameAndId"
                        :placeholder="unSaleAttrList.length?`您还有${unSaleAttrList.length}个未选择`:'没得选啦'" clearable
                        filterable>
                        <el-option v-for="(sale,index) in unSaleAttrList" :key="sale.id" :label="sale.name"
                            :value="`${sale.id}:${sale.name}`"></el-option>
                    </el-select>
                    <el-button type="primary" size="default" :icon="Plus" @click="addSaleAttr"
                        style="margin-left: 10px;" :disabled="!unSaleAttrNameAndId">添加销售属性
                    </el-button>

                    <el-table border stripe style="margin:10px 0;" :data="spuHasSaleAttrList">
                        <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                        <el-table-column label="属性名" width="160" prop="saleAttrName"></el-table-column>
                        <el-table-column label="属性值列表">
                            <template #="{row,$index}">
                                <el-tag v-for="(tag,index) in row.spuSaleAttrValueList" :key="tag.id" class="mx-1"
                                    closable :type="tag.type" style="margin: 5px 5px 10px 0;"
                                    @close="row.spuSaleAttrValueList.splice(index,1)">
                                    {{ tag.saleAttrValueName }}
                                </el-tag>
                                <el-input v-if="row.flag" v-model="row.inputValue" placeholder="请输入属性值" size="small"
                                    style="width: 80px;" clearable @blur="toLook(row)"></el-input>
                                <el-button v-else type="primary" size="small" @click="toEdit(row)" :icon="Plus">
                                </el-button>

                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="160">
                            <template #="{row,$index}">
                                <el-button type="danger" size="small" :icon="Delete"
                                    @click="spuHasSaleAttrList.splice($index,1)"></el-button>
                            </template>

                        </el-table-column>
                    </el-table>
                    <el-button type="primary" size="default" @click="save">保存</el-button>
                    <el-button size="default" @click="cancel">取消</el-button>
                </el-form-item>
            </el-form>


        </el-card>

    </div>
</template>

<script setup lang="ts">
import { reqAddOrUpdateSpu } from '@/api/product/spu/spu'
import { ref, computed } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { reqAllAttr, reqAllTrademark, reqImgList, reqSaleAttrList } from '@/api/product/spu/spu';

// 存储全部品牌数据
let allTrademark = ref([])
// 存储全部销售属性
let allSaleAttr = ref([])
// 存储照片墙数据
let imgList = ref([])
// 存储spu已有的销售属性
let spuHasSaleAttrList = ref([])

// 存储spu所有的参数
let spuParams = ref({})

// 存储未选中的销售属性的名字和id
let unSaleAttrNameAndId = ref('')


// 照片墙信息
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 删除的钩子
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    imgList.value = uploadFiles
}
// 预览的钩子
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

// 获取所有数据的请求
const getAllInfo = async (row) => {
    let ps1 = reqAllTrademark()
    let ps2 = reqAllAttr()
    let ps3 = reqImgList(row.id)
    let ps4 = reqSaleAttrList(row.id)
    let result = await Promise.all([ps1, ps2, ps3, ps4])
    console.log(result)
    // 存储全部品牌数据
    allTrademark.value = result[0]
    // 存储全部销售属性
    allSaleAttr.value = result[1]
    //存储照片墙数据
    imgList.value = result[2].map((item) => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    // 存储spu已有的销售属性
    spuHasSaleAttrList.value = result[3]
    // 存储spu数据
    spuParams.value = row
}

// 计算未选择的销售属性
const unSaleAttrList = computed(() => {
    let result = allSaleAttr.value.filter((item) => {
        return spuHasSaleAttrList.value.every((item1) => {
            return item.name != item1.saleAttrName
        })
    })
    return result
})
// 点击添加销售属性按钮
const addSaleAttr = () => {
    // 整理参数
    // 新增销售属性的id和名字
    const [baseSaleAttrId, saleAttrName] = unSaleAttrNameAndId.value.split(':')
    // 添加销售属性值所需要的参数对象
    let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
    // 向数组中添加一条属性
    spuHasSaleAttrList.value.push(newSaleAttr)
    // 清空下拉框
    unSaleAttrNameAndId.value = ''

}

// input失去焦点后切换查看模式
const toLook = (row) => {
    if (row.inputValue == '') {
        ElMessage({
            type: 'error',
            message: '输入内容不能为空'
        })
        row.flag = false
        return
    }
    // 若重复
    let repeat = row.spuSaleAttrValueList.find((item) => {
        return item.saleAttrValueName === row.inputValue
    })
    console.log(repeat);
    if (repeat) {
        ElMessage({
            type: 'warning',
            message: '输入内容出现重复'
        })
        row.inputValue = ''
        row.flag = false
        return
    }

    row.flag = false
    // 新增属性值
    let newSaleAttrVal = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue
    }
    // 追加到当前属性值数组里面
    row.spuSaleAttrValueList.push(newSaleAttrVal)
    row.inputValue = ''
}
// 点击按钮切换编辑模式
const toEdit = (row) => {
    row.flag = true
    // 初始值为空
    row.inputValue = ''
}
// 点击保存按钮
const save = async () => {
    // 整理参数
    // 整理照片墙的参数
    spuParams.value.spuImageList = imgList.value.map((item) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.date) || item.url
        }
    })
    // 整理销售属性的参数
    spuParams.value.spuSaleAttrList = spuHasSaleAttrList.value
    try {
        // 发请求
        await reqAddOrUpdateSpu(spuParams.value)
        ElMessage({
            type: 'success',
            message: spuParams.value.id ? '修改成功' : '添加成功'
        })
        emit('changeShow', {
            shows: 0,
            flag: spuParams.value.id ? 'update' : 'add'
        })
        resetData()
    } catch (error) {
        ElMessage({
            type: 'error',
            message: spuParams.value.id ? '修改失败' : '添加失败'
        })
    }

}
//点击取消按钮的回调
const cancel = () => {
    emit('changeShow', {
        shows: 0,
        flag: spuParams.value.id ? 'update' : 'add'
    })
    resetData()
}

//添加SPU的回调
const initAddSpu = async(c3Id)=>{
    spuParams.value.category3Id = c3Id
    let ps1 = reqAllTrademark()
    let ps2 = reqAllAttr()
    let result = await Promise.all([ps1, ps2])
     // 存储全部品牌数据
     allTrademark.value = result[0]
    // 存储全部销售属性
    allSaleAttr.value = result[1]
}

// 清空数据的回调
const resetData = ()=>{
    spuParams.value = {}
    imgList.value= []
    spuHasSaleAttrList.value = []
}

let emit = defineEmits(['changeShow'])
defineExpose({
    getAllInfo,
    initAddSpu
})
</script>

<style scoped>

</style>